package com.jhj.springboot_exp3.service;

import com.jhj.springboot_exp3.model.CsvModel;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
@EnableScheduling
public class CsvService implements InitializingBean {

    public static Resource resource;

    /*
     * 每天凌晨2点更新数据
     */
    @Override
    @Scheduled(cron = "0 0 2 * * *")
    public void afterPropertiesSet() throws Exception {
        //爬取全球新型冠状病毒的csv文件
        RequestEntity<Void> requestEntity =
                RequestEntity.get(URI.create("https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"))
                        .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                        .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        resource = exchange.getBody();
        System.out.println("初始化数据资源！");
    }

    public List<CsvModel> getCsvList(){
        List<CsvModel> listCsv = new ArrayList<CsvModel>();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
            Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(bufferedReader);
            for (CSVRecord record : records) {
                //将对应记录添加进List中
                String State = record.get("Province/State");
                String Country = record.get("Country/Region");
                int latestTotalCases = Integer.parseInt(record.get(record.size() - 1));
                int diffFromPrevDay = Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2));
                CsvModel csvModel= new CsvModel(State, Country, latestTotalCases, diffFromPrevDay);
                listCsv.add(csvModel);
                System.out.println(State+"<<<"+Country+"<<<"+latestTotalCases+"<<<"+diffFromPrevDay);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return listCsv;
    }

}
